package cn.stylefeng.mferp.modular.business.service.impl;

import cn.stylefeng.mferp.modular.business.service.IEasyExcelService;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yzr
 * @since 2020-06-27
 */
@Service
public class EasyExcelServiceImpl implements IEasyExcelService {

    @Override
    public void download(HttpServletResponse response, List list, Class head, String name, String excelType) throws IOException {
        String thisFileName;
        ExcelWriterBuilder excelWriterBuilder;
        if(StringUtils.isNotBlank(excelType) && "03".equals(excelType)) {
            thisFileName = name + System.currentTimeMillis() + ExcelTypeEnum.XLS.getValue();
            excelWriterBuilder = EasyExcel.write(response.getOutputStream(), head).excelType(ExcelTypeEnum.XLS);
        } else {
            thisFileName = name + System.currentTimeMillis() + ExcelTypeEnum.XLSX.getValue();
            excelWriterBuilder = EasyExcel.write(response.getOutputStream(), head).excelType(ExcelTypeEnum.XLSX);;
        }
        if(StringUtils.isNotBlank(thisFileName) && excelWriterBuilder != null && list.size() > 0) {
            // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode(thisFileName, "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName);
//            response.setHeader("Pragma", "public");
//            response.setHeader("Cache-Control", "no-store");
//            response.addHeader("Cache-Control", "max-age=0");
            excelWriterBuilder.sheet(name).doWrite(list);
        }
    }
}
